package queryWrapper

import "gorm.io/gorm"

type OrPair struct {
	Key   string
	Value string
}

type WherePair struct {
	Query string
	Args  []interface{}
}

type Pair struct {
	WherePair *WherePair
	OrderPair *OrPair
}

func (w *WherePair) And(where *WherePair) *WherePair {
	if w.Query == "" {
		return where
	} else {
		if where == nil {
			return &WherePair{Query: w.Query, Args: w.Args}
		}
		return &WherePair{Query: w.Query + " AND " + where.Query, Args: append(w.Args, where.Args...)}
	}

}

func (w *WherePair) Or(where *WherePair) *WherePair {
	if w.Query == "" {
		return where
	} else {
		return &WherePair{Query: w.Query + " OR " + where.Query, Args: append(w.Args, where.Args...)}
	}
}

func ReuseWherePair(tx *gorm.DB, pair *WherePair) *gorm.DB {
	if pair != nil {
		tx = tx.Where(pair.Query, pair.Args...)
	}
	return tx
}

func ReuseOrPair(tx *gorm.DB, pair *OrPair) *gorm.DB {
	if pair != nil {
		tx = tx.Or(pair.Key, pair.Value)
	}
	return tx
}

func ReuseOrderPair(tx *gorm.DB, orders []string) *gorm.DB {
	if len(orders) == 0 {
		return tx
	}

	for _, order := range orders {
		if order != "" {
			tx = tx.Order(order)
		}
	}

	return tx
}

func ReuseSelect(tx *gorm.DB, filters []string) *gorm.DB {
	if len(filters) > 0 {
		return tx.Select(filters)
	}
	return tx
}

func ReuseOmit(tx *gorm.DB, columns []string) *gorm.DB {
	if len(columns) > 0 {
		return tx.Omit(columns...)
	}
	return tx
}
